package com.ken.common.auth.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ken.entity.base.protocol.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 授权异常处理器 - 弃用
 */
@Deprecated
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置状态码
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        //设置响应头
        httpServletResponse.addHeader("Content-Type", "application/json;charset=utf-8");
        //设置响应体
        PrintWriter writer = httpServletResponse.getWriter();
        R r = new R(HttpStatus.UNAUTHORIZED.value(), "权限不足", null);
        ObjectMapper objectMapper = new ObjectMapper();
        String result = objectMapper.writeValueAsString(r);
        writer.println(result);
        writer.flush();
        writer.close();
    }
}
